<template>
  <div class="form-card">
    <div class="card-title">会议预约流程</div>
    <div class="card-line"></div>
    <div class="card-steps"></div>
    <div class="card-tip">
      <img
        src="@/assets/images/meeting_add_tip.png"
        alt=""
      />
      <span>
        {{ hint }}
      </span>
    </div>
    <n-form
      ref="formRef"
      :model="formModel"
      :rules="rules"
      label-placement="left"
      label-width="auto"
      require-mark-placement="right-hanging"
      size="medium"
      :style="{
        maxWidth: '640px',
        margin: '0 auto'
      }"
    >
      <n-form-item
        label="申请部门"
        path="department"
      >
        <n-input
          v-model:value="formModel.department"
          placeholder="申请部门"
          disabled
        />
      </n-form-item>

      <n-form-item
        label="申请人"
        path="applicant"
      >
        <n-input
          v-model:value="formModel.applicant"
          placeholder="申请人"
          disabled
        />
      </n-form-item>

      <n-form-item
        label="预约时间"
        path="reservationTime"
      >
        <n-date-picker
          v-model:value="formModel.reservationTime"
          type="datetimerange"
          clearable
          disabled
        />
      </n-form-item>

      <n-form-item
        label="会议室"
        path="meetingRoom"
      >
        <n-input
          v-model:value="formModel.meetingRoom"
          placeholder="会议室"
          disabled
        />
      </n-form-item>

      <n-form-item
        label="内部设施"
        path="facilities"
      >
        <n-input
          v-model:value="formModel.facilities"
          placeholder="内部设施"
          disabled
        />
      </n-form-item>

      <n-form-item
        label="用途"
        path="purpose"
      >
        <n-input
          v-model:value="formModel.purpose"
          type="textarea"
          placeholder="请输入会议用途"
        />
      </n-form-item>

      <n-space
        justify="center"
        style="margin-top: 20px"
      >
        <n-button
          type="primary"
          ghost
          size="large"
          @click="handleReset"
        >
          取消
        </n-button>
        <n-button
          type="primary"
          size="large"
          @click="handleSubmit"
        >
          提交申请
        </n-button>
      </n-space>
    </n-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, onUpdated, onBeforeUpdate, watch } from 'vue'
import { useMessage } from 'naive-ui'
import dayjs from 'dayjs'
import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router'
import { useReservationStore } from '@/stores/reservationStore'
import { usePermissionStore } from '@/stores/permission'
import { sendRequest } from '@/utils/api'
import {
  NForm,
  NFormItem,
  NInput,
  NDatePicker,
  NSpace,
  NButton,
  FormInst,
  FormRules
} from 'naive-ui'

interface FormModel {
  departId: string
  department: string
  applicant: string
  reservationTime: [number, number] | null
  meetingRoom: string
  conferenceRoomId: string
  facilities: string
  purpose: string
  startTime: string
  endTime: string
}

const formRef = ref<FormInst | null>(null)
const message = useMessage()
const router = useRouter()
const route = useRoute()
const permissionStore: any = usePermissionStore()
const reservationStore = useReservationStore()

const formModel = ref<FormModel>({
  departId: '',
  department: '',
  applicant: '',
  reservationTime: null,
  meetingRoom: '',
  facilities: '',
  purpose: '',
  startTime: '',
  endTime: ''
})

const fetchUserInfo = async () => {
  try {
    const userId = permissionStore.userInfo.id as number
    console.log(permissionStore.userInfo, 2333)

    const data = await getPermissionInfo({ id: userId })
    return {
      departId: data.deptId,
      department: data.deptName,
      applicant: data.userName
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    message.error('获取用户信息失败，请重试')
    return null
  }
}

// 获取流程id
const hint = ref()
// const workFlowList = ref(' ')
const getWorkFlow = async () => {
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: 'A0578'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  // formValue.entityId = res.data.entityId
  hint.value = res.data.remark
  // workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
}

const getPermissionInfo = async (data: { id: number }) => {
  const [error, res] = await sendRequest({
    module: 'user',
    api: 'permissionInfo',
    uri: {
      userId: data.id
    }
  })
  if (res.code === 0 && res.data) {
    return res.data
  } else {
    message.error('获取信息失败')
  }
}

const rules: FormRules = {
  purpose: {
    required: true,
    message: '请输入会议用途',
    trigger: 'blur'
  }
}

const stepStatus = ref<'process' | 'finish' | 'error'>('process')

const handleSubmit = async (e: MouseEvent) => {
  e.preventDefault()
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      const formatTime = (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss') // 格式化时间为 HH:mm:ss
      const requestData = {
        applicationTime: formatTime(formModel.value.startTime), // 使用 startTime 的日期部分
        conferenceRoomId: formModel.value.conferenceRoomId, // 假设 reservationInfo 中包含 roomId
        content: formModel.value.purpose,
        deptId: formModel.value.departId, // 假设 permissionStore 中包含部门ID
        deptName: formModel.value.department,
        draft: false, // 假设不是草稿
        startTime: formatTime(formModel.value.startTime),
        endTime: formatTime(formModel.value.endTime)
      }

      const [error, res] = await sendRequest({
        module: 'meeting', // 根据实际 API 模块名称调整
        api: 'saveRoomReservation', // 根据实际 API 名称调整
        override: {
          data: requestData
        }
      })

      if (res && res.code === 0) {
        message.success('预约申请提交成功')
        // 跳转到成功页面或其他操作
        router.push('/OA/Meeting/RoomReservationsList') // 根据实际路由名称调整
      } else {
        message.error(res?.msg || '预约申请提交失败，请重试')
      }
    } else {
      message.error('请填写所有必要信息')
    }
  })
}

const handleReset = () => {
  router.back() // 返回上一页
}
const updateFormWithReservationInfo = async (reservationInfo: any) => {
  if (reservationInfo) {
    // 获取用户信息
    const userInfo = await fetchUserInfo()
    if (!userInfo) {
      router.back()
      return
    }

    formModel.value = {
      departId: userInfo.departId,
      department: userInfo.department,
      applicant: userInfo.applicant,
      reservationTime: [
        new Date(reservationInfo.startTime).getTime(),
        new Date(reservationInfo.endTime).getTime()
      ],
      meetingRoom: reservationInfo.roomName,
      conferenceRoomId: reservationInfo.roomId,
      facilities: reservationInfo.facilities,
      purpose: formModel.value.purpose, // 保留用户已输入的用途
      startTime: reservationInfo.startTime,
      endTime: reservationInfo.endTime
    }
  } else {
    message.error('缺少必要的预订信息')
    router.back() // 如果没有收到信息，返回上一页
  }
}

// 监听 reservationInfo 的变化
watch(
  () => reservationStore.reservationInfo,
  (newValue) => {
    updateFormWithReservationInfo(newValue)
  },
  { deep: true }
) // 使用深度监听以捕获对象内部的变化

onMounted(async () => {
  await updateFormWithReservationInfo(reservationStore.reservationInfo)
  getWorkFlow()
})
</script>

<style scoped lang="scss">
.form-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 928px;
  padding: 20px;
  background: #e1e1e1;
  .card-title {
    display: flex;
    align-items: center;
    width: 100%;
    color: #1d2129;
    font-size: 24px;
    font-weight: 500;
    line-height: 34px;
    &::before {
      content: '';
      display: inline-block;
      width: 4px;
      height: 18px;
      margin-right: 7px;
      border-radius: 2.5px;
      background: #6cb187;
    }
  }
  .card-line {
    width: 100%;
    height: 1px;
    margin-top: 16px;
    background-color: #fff;
  }
  .card-tip {
    display: flex;
    width: 880px;
    margin: 20px 0;
    padding: 4px 8px;
    justify-content: center;
    align-items: center;
    gap: 8px;
    border-radius: 8px;
    background: #f3f8f2;
    color: #4e5969;
    font-size: 14px;
    line-height: 34px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    img {
      width: 16px;
      height: 16px;
    }
    span {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>
